package service

import (
	"fmt"
	"gin_server/pkg/redis"

	"github.com/mojocn/base64Captcha"
)

type CaptchaResponse struct {
	CaptchaID  string `json:"captcha_id"`
	CaptchaImg string `json:"captcha_img"`
}

type CaptchaService struct{}

func NewCaptchaService() *CaptchaService {
	return &CaptchaService{}
}

// GenerateCaptcha 生成图形验证码
func (s *CaptchaService) GenerateCaptcha() (CaptchaResponse, error) {
	// 字符串验证码
	driver := &base64Captcha.DriverString{
		Height:          40,
		Width:           120,
		ShowLineOptions: base64Captcha.OptionShowHollowLine,
		NoiseCount:      0,
		Source:          "0123456789abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ",
		Length:          4,
		Fonts:           []string{"wqy-microhei.ttc"},
	}
	driver = driver.ConvertFonts()
	id, b64s, answer, err := base64Captcha.NewCaptcha(driver, base64Captcha.DefaultMemStore).Generate()
	if err != nil {
		return CaptchaResponse{}, err
	}

	// 将验证码存储到Redis，过期时间5分钟
	captchaKey := fmt.Sprintf("captcha:%s", id)
	err = redis.SetWithExpire(captchaKey, answer, 5)
	if err != nil {
		return CaptchaResponse{}, err
	}

	return CaptchaResponse{
		CaptchaID:  id,
		CaptchaImg: b64s,
	}, nil
}

// VerifyCaptcha 验证图形验证码
func (s *CaptchaService) VerifyCaptcha(captchaID, value string) (bool, error) {
	// 从Redis获取验证码
	captchaKey := fmt.Sprintf("captcha:%s", captchaID)
	answer, err := redis.GetString(captchaKey)
	if err != nil {
		return false, fmt.Errorf("验证码不存在或已过期")
	}

	// 验证成功后删除验证码，防止重复使用
	redis.Delete(captchaKey)

	// 比较验证码（忽略大小写）
	return answer == value, nil
}
